/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package readwriteofficedocs;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.HashMap;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Paragraph;
import org.apache.poi.hwpf.usermodel.Range;

/**
 *
 * @author Administrador
 */
public class OtroEjemplo {

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        try {
            HashMap<String,String> keys = new HashMap<String, String>();
            keys.put("NOMBRE_USUARIO", "WALTER");
            keys.put("NRO_DNI", "43769130");
            File inputFile = new File("C:\\plantilla.doc");
            FileInputStream fileInputStream = new FileInputStream(inputFile);
            BufferedInputStream buffInputStream = new BufferedInputStream(fileInputStream);
            HWPFDocument document = new HWPFDocument(buffInputStream);

            Range range = document.getRange();

            int numParagraphs = range.numParagraphs();

            for (int i = 0; i < numParagraphs; i++) {
                Paragraph para = range.getParagraph(i);
                String paraText = para.text();
                for (String key : keys.keySet()) {
                    paraText = replaceText(key,keys.get(key), paraText);
                }
                para.replaceText(para.text(), paraText, 0);
                
            }
            FileOutputStream fos = new FileOutputStream("C:\\nuevaDATA.doc");
            
            document.write(fos);
            fos.flush();
            fos.close();
        } catch (Exception e) {
        }


    }

    private static String replaceText(String key, String value, String text) {
    int index = 0;
    while((index = text.indexOf(key)) >= 0) {
        text = text.substring(0, index) + value + text.substring(index + key.length());
    }
    return(text);
}
}
